import React, { useState, useEffect } from 'react'
import { Space, Button, message } from 'antd'
import style from './Index.module.less'
import { awaitWrap, confirmAction } from '@js/tool'
import { createApproveRequest } from './ajax'

async function createHandle (flowName, caseid, setLoading = () => {}, callback = () => {}) {
  const hide = message.loading('新增呈批中', 120)
  setLoading(true)
  const [e] = await awaitWrap(createApproveRequest(flowName, caseid, callback))
  hide()
  setLoading(false)
  if (e !== null) {
    message.warning(e.message)
  }
}

function Main ({ flowClass, instanceList, caseid, refreshList = () => {} }) {
  const [creatable, setCreatable] = useState(false)
  const [unique, setUnique] = useState(false)
  const [sameTime, setSameTime] = useState(false)
  const [allFinish, setAllFinish] = useState(false)
  const [loading, setLoading] = useState(false)
  const clickHandle = () => confirmAction(`您确定要${flowClass.start_title}吗？`, () => createHandle(flowClass.name, caseid, setLoading, refreshList))
  useEffect(() => {
    if (flowClass) {
      setUnique(flowClass.biz_unique === 1)
      setSameTime(flowClass.biz_sametime === 1)
    }
  }, [flowClass])
  useEffect(() => {
    setAllFinish(instanceList.every(li => li.status === '完成'))
  }, [instanceList])
  useEffect(() => {
    if (unique && instanceList.length === 0) { // 唯一呈批且未创建呈批
      setCreatable(true)
    } else if (!unique && sameTime) { // 非唯一呈批，且可以同时创建多个
      setCreatable(true)
    } else if (!unique && !sameTime && allFinish) { // 非唯一呈批，不允许同时创建多个
      setCreatable(true)
    } else {
      setCreatable(false)
    }
  }, [instanceList, unique, sameTime, allFinish])
  if (!creatable) {
    return <div />
  }
  if (instanceList.length > 0) {
    return (
      <div className={style['add-button']}>
        <Button type='dashed' loading={loading} block onClick={clickHandle}>+ {flowClass.name}</Button>
      </div>
    )
  }
  return (
    <div className={style.container}>
      <span className={style['flow-title']}>{flowClass.name}</span>
      <Space>
        <Button type='primary' onClick={clickHandle} loading={loading}>{flowClass.start_title}</Button>
      </Space>
    </div>
  )
}

export default Main
